package com.group.project.hrms.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;


public class HttpUtils {


    /**
     * 发送Get请求
     * @param restTemplate RestTemplate对象，在需要使用该方法时通过Spring容器注入
     * @param url url
     * @return 响应Body，需要使用JSONObject.parseObject(body, < T >.class)进行相应的转换
     */
    public static String doGetRequest(RestTemplate restTemplate, String url){

        //发起get请求
        ResponseEntity<String> stringResponseEntity = null;
        try {
            stringResponseEntity = restTemplate.getForEntity(url, String.class);
        } catch (RestClientException e) {
            e.printStackTrace();
        }

        //获取http状态码
        int statusCodeValue = stringResponseEntity.getStatusCodeValue();

        if(statusCodeValue == 200){
            //获取返回体
            return stringResponseEntity.getBody();
        }else {
            return "F"; //Fail
        }

    }


    /**
     * 发送Post请求
     * @param restTemplate RestTemplate对象，在需要使用该方法时通过Spring容器注入
     * @param url url
     * @param token token
     * @param param 请求参数体，需要在调用该方法的地方构建（JSONObject jsonObject = new JSONObject();jsonObject.put("UserName",USER_NAME);jsonObject.put("Password",PASS_WORD);）
     * @return 响应Body，需要使用JSONObject.parseObject(body, < T >.class)进行相应的转换
     */
    public static String doPostRequest(RestTemplate restTemplate, String url, String token, JSONObject param){

        //添加请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type","application/json");

        //组装请求头和参数
        HttpEntity<String> formEntity = new HttpEntity<>(JSON.toJSONString(param), headers);

        //发起post请求
        ResponseEntity<String> stringResponseEntity = null;
        try {
            stringResponseEntity = restTemplate.postForEntity(url + "?access_token=" + token, formEntity, String.class);
        } catch (RestClientException e) {
            e.printStackTrace();
        }

        //获取http状态码
        int statusCodeValue = stringResponseEntity.getStatusCodeValue();

        if(statusCodeValue == 200){
            //获取返回体
            return stringResponseEntity.getBody();
        }else {
            return "F"; //Fail
        }
    }


}
